<?php
/**
 * Created by PhpStorm.
 * User: junyv
 * Date: 2017/4/15
 * Time: 11:08
 */

namespace app\home\controller\user;


class Common extends \app\home\controller\Base
{
    protected $_name;
    protected $errMsg;
    protected $userInfo;
    public function _initialize()
    {
        parent::_initialize();
        $this->checkUserInfo();
        $this->getUserInfo();
    }
    private function checkUserInfo(){
        $user = cookie('userInfo');
        if(!$user){
            $this->error('请先登录后再操作');
        }else{
            $this->userInfo = $user;
        }
    }
    protected function getUserInfo($field='id,username,nickname,headimgurl,chuzu,chushou,login_time'){
        $user = cookie('userInfo');
        $where['id'] = $user['id'];
        $info = model('user')->where($where)->field($field)->find();
        if(!$info){
            $this->error('用户不存在',url('user.login/index'));
        }
        if(empty($info['headimgurl'])){
            $info['headimgurl'] = '/static/home/images/head_logo.png';
        }
        $this->assign('baseInfo',$info);
        return $info;
    }
    //添加方法
    public function add(){
        if(request()->isAjax()){
            $response = $this->fetch();
            $this->ajaxReturn(1,'',$response);
        }else{
            return $this->fetch();
        }
    }
    //执行添加操作
    public function addDo(){
        $obj = model($this->_name);
        if(request()->isPost()){
            $data = input('post.');
            $img  = $this->_uploadImg($data);
            if($img){
                $data['img'] = $img;
            }
            if($obj->allowField(true)->save($data)){
                request()->isAjax() ? $this->ajaxReturn(1,'添加成功','','add') : $this->success('添加成功');
            }else{
                request()->isAjax() ? $this->ajaxReturn(0,'添加失败','') : $this->error('添加失败');
            }
        }
    }
    //编辑
    public function edit(){
        $obj = model($this->_name);
        $pk  = $obj->getPk();
        $id  = input($pk);
        if($id){

            $info = $obj->find($id);
            $this->assign('info',$info);
            if(request()->isAjax()){
                $response = $this->fetch();
                $this->ajaxReturn(1,'',$response);
            }else{
                return $this->fetch();
            }
        }else{
            request()->isAjax() ? $this->ajaxReturn(0,'参数错误') : $this->error('参数错误');
        }

    }
    //保存编辑内容
    public function editDo(){
        $obj = model($this->_name);
        if(request()->isPost()){
            $data = input('post.');
            if(!isset($data['id']) || empty($data['id'])){
                request()->isAjax() ? $this->ajaxReturn(0,'参数错误') : $this->error('参数错误');
            }
            $img = $this->_uploadImg();
            if($img){
                $data['img'] = $img;
            }
            //allowField 过滤非数据表字段
            if($obj->allowField(true)->save($data,['id'=>$data['id'],'user_id'=>$this->userInfo['id']])){
                request()->isAjax() ? $this->ajaxReturn(1,'编辑成功','','edit') : $this->success('编辑成功');
            }else{
                request()->isAjax() ? $this->ajaxReturn(0,'编辑失败','') : $this->error('编辑失败');
            }
        }
    }
    /**
     * 删除
     */
    public function delete(){
        $mod = model($this->_name);
        $pk  = $mod->getPk();
        $ids = trim(input($pk), ',');
        if ($ids) {
            if (0 !== $mod::destroy([$pk=>['in',$ids],'user_id'=>$this->userInfo['id']],false)) {
                request()->isAjax() && $this->ajaxReturn(1, '删除成功');
                $this->success('删除成功');
            } else {
                $str = $this->errMsg ? $this->errMsg : '删除失败';
                request()->isAjax() && $this->ajaxReturn(0, $str);
                $this->error('删除失败');
            }
        } else {
            request()->isAjax() && $this->ajaxReturn(0, '参数错误');
            $this->error('参数错误');
        }
    }
    //异步上传图片
    public function ajaxUploadImg(){
        $img = $this->_uploadImg();
        if($img){
            $this->ajaxReturn(1,'上传成功',$img);
        }else{
            $this->ajaxReturn(0,'请选择图片');
        }
    }
    protected function _uploadImg($data=[]){
        $img = '';
        if(isset($_FILES['img']) && !empty($_FILES['img']['name'])){
            $file = request()->file('img');
            // 移动到框架应用根目录/public/uploads/ 目录下
            $path = config('uploads_path').$this->_name.'/';
            $info = $file->move(ROOT_PATH.$path);
            if($info){
                $img = '/uploads/'.$this->_name.'/'.str_replace('\\','/',$info->getSaveName());
            }else{
                // 上传失败获取错误信息
                request()->isAjax() ? $this->ajaxReturn(0,$file->getError()) : $this->error($file->getError());
            }
        }elseif(isset($data['thumb'])){
            $content = stripslashes($data['info']);
            if(preg_match_all("/(src)=([\"|']?)([^ \"'>]+\.(gif|jpg|jpeg|bmp|png))\\2/i", $content, $matches)) {
                $img = $matches[3][0];
            }
        }
        return $img;
    }
    protected function ajaxReturn($status=0,$msg='',$data='',$id=''){
        $return['status'] = $status;
        $return['msg']    = $msg;
        $return['data']   = $data;
        $return['dialog'] = $id;//用于关闭弹出框
        header('Content-Type:application/json; charset=utf-8');
        exit(json_encode($return));
    }
}